from django.db import models
from django.contrib.auth.models import AbstractUser
from permissions.models import Menu


class User(AbstractUser):
    ROLE_CHOICES = (
        ('supremo', '超级'),
        ('manager', '管理'),
        ('developer', '开发'),
        ('ordinary', '普通'),
    )
    name = models.CharField(max_length=32, verbose_name='姓名', help_text='姓名', null=True)
    phone = models.CharField(max_length=11, verbose_name='电话', help_text='电话', null=True)
    role = models.CharField(max_length=32, verbose_name='角色', help_text='成员角色',
                            choices=ROLE_CHOICES, default='ordinary')
    id_rsa_key = models.TextField(null=True, help_text='认证私钥', verbose_name='认证私钥')
    id_rsa_pub = models.TextField(null=True, help_text='认证公钥', verbose_name='认证公钥')

    def __str__(self):
        user = self.name if self.name else self.username
        return user

    class Meta:
        verbose_name_plural = verbose_name = "用户"
        ordering = ["id"]
        db_table = 'auth_user'
        permissions = (
            ('view_user', 'cat view user'),
        )

    def get_view_permissions(self):
        """
        获取用户所属组的前端权限，在获取用户信息时有调用
        """
        if self.is_superuser:
            return Menu.objects.all()
        return Menu.objects.filter(groups__in=self.groups.all())
